<template>
  <!-- 弹窗对话框，根据 mode 的不同显示不同的标题，支持新增、编辑和查看操作 -->
  <t-drawer
    :visible="dialogVisible"
    :header="mode == 'new' ? '新增' : mode == 'edit' ? '编辑' : mode == 'view' ? '查看' : ''"
    @confirm="handleSubmit"
    :confirmBtn="EDIT_FORM_SAVE_BUTTON(mode)"
    @close="handleClose"
    size="90%"
  >
    <t-loading text="加载中..." size="small" :loading="pageData.loading">
      <FormInfo v-if="mode !== 'new'">
        <template #left>订单号：{{ pageData.formData.orderId }}</template>
        <template #content>
          <t-form>
            <t-row>
              <t-col :span="3">
                <t-form-item label="创建人">
                  <div class="form__text">{{ pageData.formData.createdByName }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="3">
                <t-form-item label="创建日期">
                  <div class="form__text">{{ dayjs(pageData.formData.createdTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="3">
                <t-form-item label="更新人" v-if="pageData.formData.updatedByName !== null">
                  <div class="form__text">{{ pageData.formData.updatedByName }}</div>
                </t-form-item>
              </t-col>
              <t-col :span="3">
                <t-form-item label="更新日期" v-if="pageData.formData.updatedTime !== null">
                  <div class="form__text">{{ dayjs(pageData.formData.updatedTime).format("YYYY-MM-DD HH:mm:ss") }}</div>
                </t-form-item>
              </t-col>
            </t-row>
          </t-form>
        </template>
      </FormInfo>
      <t-form
        ref="formInstance"
        :rules="pageData.formRules"
        :disabled="pageData.readOnly"
        :data="pageData.formData"
        :labelWidth="120"
      >
        <t-tabs v-model="pageData.activeTab">
          <t-tab-panel :value="0" label="基本和采购销售信息">
            <div class="form__container">
              <FormInfo>
                <template #left>基本信息</template>
                <template #right>【{{ exchange.lastDate }} 更新】美元汇率：{{ pageData.usdData?.price }}</template>
                <template #content>
                  <t-space direction="vertical" style="width: 100%" size="large">
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="订单名称" name="orderName">
                          <t-input
                            :showLimitNumber="true"
                            v-if="!pageData.readOnly"
                            v-model="pageData.formData.orderName"
                            maxlength="50"
                          />
                          <div v-else class="form__text">{{ pageData.formData.orderName }}</div>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="客户" name="orderCustomerName">
                          <InputSelect
                            @onClick="handleCustomerShow"
                            placeholder="点击右边按钮选择"
                            v-if="!pageData.readOnly"
                            :value="pageData.formData.orderCustomerName"
                          />
                          <div v-else class="form__text">{{ pageData.formData.orderCustomerName }}</div>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="接单日期" name="orderDate">
                          <t-date-picker
                            clearable
                            :showLimitNumber="true"
                            v-if="!pageData.readOnly"
                            v-model="pageData.formData.orderDate"
                            style="width: 100%"
                          />
                          <div v-else class="form__text">
                            {{ dayjs(pageData.formData.orderDate).format("YYYY-MM-DD HH:mm:ss") }}
                          </div>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="签约主体" name="orderCustomerType">
                          <t-select v-if="!pageData.readOnly" v-model="pageData.formData.orderCustomerType">
                            <t-option
                              v-for="item in pageData.customerTypeSelectData"
                              :key="item"
                              :label="item.label"
                              :value="item.value"
                            ></t-option>
                          </t-select>
                          <div v-else class="form__text">{{ pageData.formData.orderCustomerTypeName }}</div>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="合同编号" name="contractNo">
                          <t-input
                            :showLimitNumber="true"
                            v-if="!pageData.readOnly"
                            v-model="pageData.formData.contractNo"
                            maxlength="100"
                          />
                          <div v-else class="form__text">{{ pageData.formData.contractNo }}</div>
                        </t-form-item>
                      </t-col>
                    </t-row>
                  </t-space>
                </template>
              </FormInfo>

              <!-- 销售信息 -->
              <FormInfo>
                <template #left>销售信息</template>
                <template #content>
                  <t-space direction="vertical" style="width: 100%" size="large">
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="装运口岸" name="loadPort">
                          <t-input
                            :showLimitNumber="true"
                            v-if="!pageData.readOnly"
                            v-model="pageData.formData.loadPort"
                            maxlength="30"
                          />
                          <div v-else class="form__text">{{ pageData.formData.loadPort }}</div>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="运抵口岸" name="unloadPort">
                          <t-input
                            :showLimitNumber="true"
                            v-if="!pageData.readOnly"
                            v-model="pageData.formData.unloadPort"
                            maxlength="30"
                          />
                          <div v-else class="form__text">{{ pageData.formData.unloadPort }}</div>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="目的国" name="targetCountry">
                          <InputSelect
                            @onClick="handleRegionShow"
                            v-if="!pageData.readOnly"
                            :value="pageData.formData.targetCountry"
                          />
                          <div v-else class="form__text">{{ pageData.formData.targetCountry }}</div>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="交货期限" name="deliveryTerm">
                          <t-date-picker
                            clearable
                            :showLimitNumber="true"
                            v-if="!pageData.readOnly"
                            v-model="pageData.formData.deliveryTerm"
                            style="width: 100%"
                          />
                          <div v-else class="form__text">
                            {{ dayjs(pageData.formData.deliveryTerm).format("YYYY-MM-DD HH:mm:ss") }}
                          </div>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="销售价币种" name="currency">
                          <t-space style="width: 100%" size="large">
                            <t-select v-model="pageData.formData.currency"
                              ><t-option
                                :value="item.value"
                                :label="item.label"
                                v-for="item in CURRENCY_LIST"
                                :key="item.value"
                            /></t-select>
                            <t-input-adornment prepend="1 USD =" append="CNY">
                              <t-input-number
                                :min="0"
                                :decimalPlaces="2"
                                theme="column"
                                v-model="pageData.formData.currencyRate"
                            /></t-input-adornment>
                          </t-space>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="交货方式" name="deliveryMethod">
                          <t-space>
                            <t-select
                              v-if="!pageData.readOnly"
                              v-model="pageData.formData.deliveryMethod"
                              :options="pageData.orderIncotermsDict"
                            />
                            <div class="form__text" v-else>
                              {{ getValueBySelectData(pageData.orderIncotermsDict, pageData.formData.deliveryMethod) }}
                            </div>
                            <t-input-adornment prepend="港口" v-if="!pageData.readOnly">
                              <t-input
                                :showLimitNumber="true"
                                v-model="pageData.formData.deliveryPort"
                                maxlength="50"
                              />
                            </t-input-adornment>
                            <div class="form__text" v-else>
                              {{ pageData.formData.deliveryPort }}
                            </div>
                          </t-space>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="支付时间" name="payTime">
                          <t-space style="width: 100%">
                            <t-select
                              v-model="pageData.formData.payTimeMethod"
                              :options="pageData.orderPayTimeWayDict"
                            />
                            <t-input-adornment append="天">
                              <t-input-number
                                :min="0"
                                theme="column"
                                v-model="pageData.formData.payTime"
                                :decimalPlaces="0"
                              />
                            </t-input-adornment>
                          </t-space>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="支付方式" name="payMethod">
                          <t-radio-group v-model="pageData.formData.payMethod">
                            <t-radio-button :value="0">电汇</t-radio-button>
                            <t-radio-button :value="1">信用证</t-radio-button>
                            <t-radio-button :value="2">托收赊销</t-radio-button>
                            <t-radio-button :value="3">其他支付方式</t-radio-button>
                          </t-radio-group>
                        </t-form-item>
                      </t-col>
                    </t-row>
                  </t-space>
                </template>
              </FormInfo>

              <FormInfo>
                <template #left>采购信息</template>
                <template #content>
                  <t-space direction="vertical" style="width: 100%" size="large">
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="增值税率" name="taxRate">
                          <t-input
                            suffix="%"
                            v-if="!pageData.readOnly"
                            v-model="pageData.formData.taxRate"
                            type="number"
                          />
                          <div v-else class="form__text">{{ pageData.formData.taxRate }}%</div>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="供应商" name="providerName">
                          <InputSelect
                            @onClick="handleProviderShow"
                            v-if="!pageData.readOnly"
                            :value="pageData.formData.providerName"
                            style="width: 100%"
                          />
                          <div v-else class="form__text">{{ pageData.formData.providerName }}</div>
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="采购价币种" name="purchaseCurrency">
                          <t-select
                            v-if="!pageData.readOnly"
                            v-model="pageData.formData.purchaseCurrency"
                            :options="CURRENCY_LIST"
                          />
                          <div v-else class="form__text">
                            {{ getValueBySelectData(CURRENCY_LIST, pageData.formData.purchaseCurrency) }}
                          </div>
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="交货地点" name="purchaseDeliveryType">
                          <t-space>
                            <t-select
                              v-if="!pageData.readOnly"
                              v-model="pageData.formData.purchaseDeliveryType"
                              :options="pageData.orderIncotermsDict"
                            />
                            <div class="form__text" v-else>
                              {{
                                getValueBySelectData(
                                  pageData.orderIncotermsDict,
                                  pageData.formData.purchaseDeliveryType
                                )
                              }}
                            </div>
                            <t-input-adornment v-if="!pageData.readOnly" prepend="港口">
                              <t-input
                                :showLimitNumber="true"
                                v-if="!pageData.readOnly"
                                v-model="pageData.formData.purchaseDeliveryPort"
                                maxlength="50"
                              />
                            </t-input-adornment>
                            <div class="form__text" v-else>
                              {{ pageData.formData.purchaseDeliveryPort }}
                            </div>
                          </t-space>
                        </t-form-item>
                      </t-col>
                    </t-row>
                  </t-space>
                </template>
              </FormInfo>
            </div>
          </t-tab-panel>
          <t-tab-panel :value="1" label="商品信息">
            <div class="form__container">
              <FormTable
                row-key="localUUID"
                :buttons="pageData.goodsButtons"
                :footData="[{}]"
                :tableData="pageData.formData.products"
                :columns="pageData.goodsColumns"
                @currentChange="handleGoodsTableSelectChange"
              >
                <template #rowOperations="{ row }">
                  <div v-if="row.hasDeleted === 0" class="form-table__row_operations">
                    <t-link variant="text" theme="danger" @click="handleDeleteGood(row)" :disabled="pageData.readOnly"
                      >删除</t-link
                    >
                  </div>
                  <div v-else>
                    <t-link theme="danger" variant="text" @click="handleUnDeleteGood(row)">撤销删除</t-link>
                  </div>
                </template>
              </FormTable>
            </div>
          </t-tab-panel>
          <t-tab-panel :value="2" label="付款申请">
            <div class="form__container">
              <FormInfo>
                <template #left>合同上传</template>
                <template #content>
                  <t-form-item :labelWidth="120" label="采购合同" name="purchaseContractsId">
                    <t-upload
                      theme="file-flow"
                      :withCredentials="true"
                      :auto-upload="true"
                      :multiple="false"
                      :request-method="handlePurchaseContractsFileUpload"
                      v-model:files="pageData.purchaseContractsFileList"
                      @remove="handlePurchaseContractsFileUploadRemove"
                      :max="1"
                    />
                  </t-form-item>
                  <t-form-item :labelWidth="120" label="销售合同" name="saleContractsId">
                    <t-upload
                      theme="file-flow"
                      :withCredentials="true"
                      :auto-upload="true"
                      :multiple="false"
                      :request-method="handleSaleContractsFileUpload"
                      v-model:files="pageData.saleContractsFileList"
                      @remove="handleSaleContractsFileUploadRemove"
                      :max="1"
                    />
                  </t-form-item>
                </template>
              </FormInfo>

              <FormInfo>
                <template #left>报关单文件</template>
                <template #content>
                  <t-form-item :labelWidth="120" label="上传报关单" name="customsDocId">
                    <t-upload
                      theme="file-flow"
                      :withCredentials="true"
                      :auto-upload="true"
                      :multiple="false"
                      :request-method="handleCustomsDocFileUpload"
                      v-model:files="pageData.customsDocFileList"
                      @remove="handleCustomsDocFileUploadRemove"
                      :max="1"
                    />
                  </t-form-item>
                </template>
              </FormInfo>

              <FormInfo>
                <template #left>电子发票附件</template>
                <template #content>
                  <t-form-item :labelWidth="120" label="上传电子发票" name="ticketDocId">
                    <t-upload
                      theme="file-flow"
                      :withCredentials="true"
                      :auto-upload="true"
                      :multiple="false"
                      :request-method="handleTicketDocFileUpload"
                      v-model:files="pageData.ticketDocFileList"
                      @remove="handleTicketDocFileUploadRemove"
                      :max="1"
                    />
                  </t-form-item>
                </template>
              </FormInfo>

              <FormInfo>
                <template #left>提单附件</template>
                <template #content>
                  <t-form-item :labelWidth="120" label="提单日期" name="billDate">
                    <t-date-picker v-model="pageData.formData.billDate" />
                  </t-form-item>
                  <t-form-item :labelWidth="120" label="上传提单" name="billDocId">
                    <t-upload
                      theme="file-flow"
                      :withCredentials="true"
                      :auto-upload="true"
                      :multiple="false"
                      :request-method="handleBillDocFileUpload"
                      v-model:files="pageData.billDocFileList"
                      @remove="handleBillDocFileUploadRemove"
                      :max="1"
                    />
                  </t-form-item>
                </template>
              </FormInfo>

              <FormInfo>
                <template #left>保证金信息</template>
                <template #content>
                  <t-space direction="vertical" style="width: 100%" size="large">
                    <t-row>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="保证金比例" name="marginRate">
                          <t-input-number suffix="%" :min="0" v-model="pageData.formData.marginRate" theme="column" />
                        </t-form-item>
                      </t-col>
                      <t-col :span="6">
                        <t-form-item :labelWidth="120" label="保证金" name="marginAmount">
                          <t-input-number
                            theme="column"
                            :min="0"
                            style="width: 100%"
                            v-model="pageData.formData.marginAmount"
                            :decimalPlaces="2"
                          />
                        </t-form-item>
                      </t-col>
                    </t-row>
                    <t-row>
                      <t-col :span="12">
                        <t-form-item
                          :labelWidth="120"
                          label="保证金水单"
                          name="marginDocIds"
                          help="选中文件后，需要先点击上传，然后才能保存付款申请。"
                        >
                          <t-upload
                            theme="file-flow"
                            :withCredentials="true"
                            :auto-upload="false"
                            :multiple="true"
                            :isBatchUpload="false"
                            :request-method="handleMarginDocFileUpload"
                            @success="handleMarginDocFileUploadSuccess"
                            :uploadAllFilesInOneRequest="false"
                            v-model:files="pageData.marginDocFileList"
                            @remove="handleMarginDocFileUploadRemove"
                            :max="5"
                          />
                        </t-form-item>
                      </t-col>
                    </t-row>
                  </t-space>
                </template>
              </FormInfo>
            </div>
          </t-tab-panel>
          <t-tab-panel :value="3" label="备注信息">
            <div class="form__container">
              <t-form
                :rules="pageData.formRules"
                :disabled="pageData.readOnly"
                :data="pageData.formData"
                :labelWidth="120"
              >
                <t-form-item label="备注" name="remark">
                  <t-textarea v-if="!pageData.readOnly" v-model="pageData.formData.remark" :autosize="{ minRows: 5 }" />
                  <div v-else class="form__text">
                    {{ pageData.formData.remark }}
                  </div>
                </t-form-item>
              </t-form>
            </div>
          </t-tab-panel>
        </t-tabs>
      </t-form>
    </t-loading>
  </t-drawer>

  <SelectTable
    v-if="pageData.customer.show"
    :showDialog="pageData.customer.show"
    :loading="pageData.customer.loading"
    title="选择客户"
    mode="table"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.customer.data.records"
    :columns="customerColumns"
    @onConfirm="handleCustomerConfirm"
    @onCancel="handleCustomerClose"
    :pagination="pageData.customer.pagination"
    :filter-value="pageData.customer.filterValue"
    @filter-change="handleCustomerFilterChange"
    @page-change="handleCustomerPageChange"
  />

  <SelectTable
    v-if="pageData.region.show"
    title="选择国家/地区"
    :loading="pageData.region.loading"
    :showDialog="pageData.region.show"
    width="60vw"
    zIndex="3500"
    rowSelectionType="single"
    :tableData="pageData.region.data.records"
    :columns="pageData.region.columns"
    @onConfirm="handleRegionConfirm"
    @onCancel="handleRegionClose"
    :pagination="pageData.region.pagination"
    @page-change="handleRegionPageChange"
    :filter-value="pageData.region.filterValue"
    @filter-change="handleRegionFilterChange"
  />

  <SelectTable
    title="选择供应商"
    v-if="pageData.provider.show"
    :showDialog="pageData.provider.show"
    :loading="pageData.provider.loading"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.provider.data.records"
    :columns="providerColumns"
    @onConfirm="handleProviderConfirm"
    @onCancel="handleProviderClose"
    :pagination="pageData.provider.pagination"
    @page-change="handleProviderPageChange"
    :filter-value="pageData.provider.filterValue"
    @filter-change="handleProviderFilterChange"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, ref, toRaw, watch } from "vue";
import { MessagePlugin, type FormInstanceFunctions, type TableProps } from "tdesign-vue-next";

// TS 类型文件
import type { ISelectDataType, ISelectTableGroups } from "@/types";

// 工具函数
import dayjs from "dayjs";
import { http } from "@/utils/fetch";
import { v4 as uuidv4 } from "uuid";
import { generateFormattedNumber, getValueBySelectData, newPrecision } from "@/utils/tools";

// 常量
import { CURRENCY_LIST, PAGINATION_VALUE } from "@/common/constants";
import { EDIT_FORM_SAVE_BUTTON } from "@/common/constants";

// API
import { uploadFileMany } from "@/api/file";
import { getRegionList } from "@/api/region";
import { getDictValue } from "@/api/dict";
import { getCustomerList } from "@/api/cas";

// 业务数据
import { tableColumns as customerColumns } from "@/pages/Dashboard/CAS/Customer/components/columns";
import { tableColumns as providerColumns } from "@/pages/Dashboard/CAS/Supplier/components/columns";

const props = defineProps(["id", "dialogVisible", "mode", "exchange", "statusDict"]);
const emits = defineEmits(["close"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const GET_FORM_PATH = "/order/findOne"; // 查询接口
const CREATE_FORM_PATH = "/order/create"; // 创建接口
const UPDATE_FORM_PATH = "/order/update"; // 更新接口

// const userStore = useUserStore();

const pageData = reactive({
  loading: true,
  readOnly: false,
  activeTab: 0,
  formData: {
    id: "",
    status: 0,
    hasDeleted: 0,
    remark: "",
    orderId: "",
    orderName: "",
    orderDate: new Date().toISOString(),
    orderCustomerType: 0,
    orderCustomerTypeName: "",
    orderCustomerId: "",
    orderCustomerName: "",
    targetCountry: "",
    loadPort: "",
    unloadPort: "",
    providerName: "",
    targetCountryId: "",
    purchaseDeliveryPort: "",
    deliveryTerm: new Date().toISOString(),
    currency: 1,
    currencyRate: 0,
    deliveryMethod: 0,
    deliveryPort: "",
    payTimeMethod: 0,
    payTime: 1,
    payMethod: 0,
    otherPayMethod: "",
    providerId: "",
    taxRate: 0,
    purchaseCurrency: 0,
    purchaseDeliveryType: 0,
    products: [],
    createdTime: "",
    createdBy: "",
    updatedBy: "",
    updatedTime: "",
    createdByName: "",
    updatedByName: "",
    hasExpress: false,
    customer: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      englishName: "",
      englishNickname: "",
      englishAddress: "",
      country: "",
      customsId: "",
      mainBusiness: "",
      market: "",
      name: "",
      nickName: "",
      address: "",
      province: "",
      city: "",
      chinaMainBusiness: "",
      chinaMainMarket: "",
      creditCode: "",
      legalPerson: "",
      registerName: "",
      type: "",
      registerTime: "",
      registerLimitTimeStart: "",
      registerLimitTimeEnd: "",
      registerMoney: "",
      registerAddress: "",
      registerBusiness: "",
      registerLicenseId: "",
      onlineShops: [],
      contacts: [],
      registerLicense: {},
      customerName: "",
      customerNo: "",
      qualificationFiles: [],
      globalQualificationFiles: [],
      globalContacts: []
    },
    provider: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      name: "",
      nickName: "",
      address: "",
      englishName: "",
      englishNickName: "",
      englishAddress: "",
      country: "",
      province: "",
      city: "",
      mainBusiness: "",
      market: "",
      creditCode: "",
      legalPerson: "",
      registerName: "",
      type: "",
      registerTime: "",
      registerLimitTimeStart: "",
      registerLimitTimeEnd: "",
      registerMoney: "",
      registerAddress: "",
      registerBusiness: "",
      registerLicenseId: "",
      defaultBankAccount: "",
      providerNo: "",
      registerLicense: {
        id: "",
        createdTime: "",
        createdBy: "",
        status: 0,
        remark: "",
        updatedBy: "",
        updatedTime: "",
        createdByName: "",
        updatedByName: "",
        hasDeleted: 0,
        name: "",
        fileURI: "",
        type: "",
        size: 0
      },
      totalPurchasePrice: 0,
      contacts: [
        {
          id: "",
          createdTime: "",
          createdBy: "",
          status: 0,
          remark: "",
          updatedBy: "",
          updatedTime: "",
          createdByName: "",
          updatedByName: "",
          hasDeleted: 0,
          name: "",
          phone: "",
          department: "",
          wechatId: "",
          whatsappId: "",
          job: ""
        }
      ],
      banks: [
        {
          id: "",
          createdTime: "",
          createdBy: "",
          status: 0,
          remark: "",
          updatedBy: "",
          updatedTime: "",
          createdByName: "",
          updatedByName: "",
          hasDeleted: 0,
          openingBank: "",
          openingBankAccount: "",
          bankAddress: "",
          bankSwiftNo: "",
          country: "",
          currencies: "",
          defaultAccount: true,
          interBankNo: ""
        }
      ],
      qualificationFiles: [
        {
          id: "",
          createdTime: "",
          createdBy: "",
          status: 0,
          remark: "",
          updatedBy: "",
          updatedTime: "",
          createdByName: "",
          updatedByName: "",
          hasDeleted: 0,
          name: "",
          fileURI: "",
          type: "",
          size: 0
        }
      ]
    },
    // 付款申请
    saleContractsId: "",
    purchaseContractsId: "",
    customsDocId: "",
    ticketDocId: "",
    billDate: "",
    billDocId: "",
    marginRate: 0,
    marginAmount: 0,
    contractNo: "",
    marginDocIds: [],
    saleContracts: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      name: "",
      fileURI: "",
      type: "",
      size: 0
    },
    purchaseContracts: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      name: "",
      fileURI: "",
      type: "",
      size: 0
    },
    customsDoc: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      name: "",
      fileURI: "",
      type: "",
      size: 0
    },
    ticketDoc: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      name: "",
      fileURI: "",
      type: "",
      size: 0
    },
    marginDocs: [
      {
        id: "",
        createdTime: "",
        createdBy: "",
        status: 0,
        remark: "",
        updatedBy: "",
        updatedTime: "",
        createdByName: "",
        updatedByName: "",
        hasDeleted: 0,
        name: "",
        fileURI: "",
        type: "",
        size: 0
      }
    ],
    billDoc: {
      id: "",
      createdTime: "",
      createdBy: "",
      status: 0,
      remark: "",
      updatedBy: "",
      updatedTime: "",
      createdByName: "",
      updatedByName: "",
      hasDeleted: 0,
      name: "",
      fileURI: "",
      type: "",
      size: 0
    },
    totalPurchasePriceSum: 0,
    totalSalePriceSum: 0
  } as Record<string, any>,
  orderIncotermsDict: [] as ISelectDataType[],
  formRules: {
    contractNo: [{ required: true, message: "请输入合同编号", type: "error", trigger: "blur" }],
    orderName: [{ required: true, message: "请输入名称", type: "error", trigger: "blur" }],
    orderCustomerName: [{ required: true, message: "请输入客户名称", type: "error", trigger: "blur" }],
    orderDate: [{ required: true, message: "请输入接单日期", type: "error", trigger: "blur" }],
    orderCustomerType: [{ required: true, message: "请选择客户主体", type: "error", trigger: "blur" }],
    purchaseCurrency: [{ required: true, message: "请选择采购价币种", type: "error", trigger: "blur" }],
    targetCountry: [{ required: true, message: "请输入目的国", type: "error", trigger: "blur" }],
    deliveryTerm: [{ required: true, message: "请输入交货期限", type: "error", trigger: "blur" }],
    currency: [{ required: true, message: "请选择销售价币种", type: "error", trigger: "blur" }],
    taxRate: [{ required: true, message: "请输入增值税率", type: "error", trigger: "blur" }],
    providerName: [{ required: true, message: "请选择供应商", type: "error", trigger: "blur" }]
  },
  usdData: {} as Record<string, any>,
  customer: {
    show: false,
    loading: false,
    data: {},
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    },
    filterValue: {}
  } as ISelectTableGroups,
  statusDict: [] as Record<string, any>[],
  customerTypeSelectData: [
    {
      label: "请先选择客户",
      value: 0
    }
  ] as Record<string, any>[],
  goodsButtons: [
    {
      name: "新建",
      icon: "add",
      disabled: props.mode === "view",
      click: () => {
        handleNewGood();
      }
    },
    {
      name: "复制",
      icon: "copy",
      disabled: props.mode === "view",
      click: () => {
        handleCopyGood();
      }
    }
  ],
  goodsColumns: [
    {
      colKey: "name",
      title: "商品名称",
      width: 250,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          return <t-input maxlength={120} v-model={row.name}></t-input>;
        } else {
          return row.name;
        }
      },
      foot: () => {
        return <b>合计</b>;
      }
    },

    {
      colKey: "englishName",
      title: "商品英文名",
      width: 250,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          return <t-input maxlength={200} v-model={row.englishName}></t-input>;
        } else {
          return row.englishName;
        }
      }
    },
    {
      colKey: "specification",
      title: "规格/型号",
      width: 200,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          return <t-input maxlength={10} v-model={row.specification}></t-input>;
        } else {
          return row.specification;
        }
      }
    },
    {
      colKey: "number",
      title: "数量",
      width: 200,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          if (!row.number) {
            row.number = 0;
          }
          row.totalPurchasePrice = newPrecision(row.purchasePrice * row.number, 2);
          row.totalSalePrice = newPrecision(row.salePrice * row.number, 2);
          return <t-input-number min={0} v-model={row.number} theme="column" />;
        } else {
          return row.number;
        }
      },
      foot: () => {
        return <div>{pageData.formData.totalProductNumber}</div>;
      }
    },
    {
      colKey: "unit",
      title: "单位",
      width: 200,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1) {
          return <t-input maxlength={10} v-model={row.unit}></t-input>;
        } else {
          return row.unit;
        }
      }
    },
    {
      colKey: "purchasePrice",
      title: "含税采购单价",
      width: 200,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1 && props.mode === "new") {
          if (!row.purchasePrice) {
            row.purchasePrice = 0;
          }
          return (
            <t-input-number min={0} v-model={row.purchasePrice} theme="column" style="width: 100%" decimalPlaces={2} />
          );
        } else {
          return row.purchasePrice;
        }
      }
    },
    {
      colKey: "totalPurchasePrice",
      title: "含税采购总价",
      width: 200,
      foot: () => {
        return <div>{pageData.formData.totalPurchasePriceSum}</div>;
      }
    },
    {
      colKey: "salePrice",
      title: "销售单价",
      width: 200,
      cell: (h, { row }) => {
        if (!pageData.readOnly && row.hasDeleted !== 1 && props.mode === "new") {
          if (!row.salePrice) {
            row.salePrice = 0;
          }
          row.totalSalePrice = newPrecision(row.salePrice * row.number, 2);
          return (
            <t-input-number v-model={row.salePrice} min={0} theme="column" style="width: 100%" decimalPlaces={2} />
          );
        } else {
          return row.salePrice;
        }
      }
    },
    {
      colKey: "totalSalePrice",
      title: "销售总价",
      width: 200,
      foot: () => {
        return <div>{pageData.formData.totalSalePriceSum}</div>;
      }
    }
  ] as TableProps["columns"],
  emptyGoodFormData: {
    id: "",
    localUUID: "",
    status: 0,
    hasDeleted: 0,
    remark: "",
    name: "",
    englishName: "",
    specification: "",
    number: 0,
    unit: "",
    purchasePrice: 0,
    salePrice: 0,
    totalPurchasePrice: 0,
    totalSalePrice: 0
  },
  goodsSelectedRowData: [],
  portTypeDict: [] as ISelectDataType[],
  region: {
    show: false,
    loading: false,
    data: {} as Record<string, any>,
    filterValue: {
      countryName: ""
    } as Record<string, any>,
    columns: [
      {
        colKey: "countryCode",
        title: "区号",
        width: 220
      },
      {
        colKey: "countryName",
        title: "国家/地区",
        width: 230,
        filter: {
          type: "input",
          resetValue: "",
          // 按下 Enter 键时也触发确认搜索
          confirmEvents: ["onEnter"],
          showConfirmAndReset: true
        }
      }
    ],
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  },
  loadPort: {
    show: false,
    loading: false,
    data: {} as Record<string, any>,
    filterValue: {
      type: [0, 1]
    } as Record<string, any>,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  },
  unloadPort: {
    show: false,
    loading: false,
    data: {} as Record<string, any>,
    filterValue: {
      type: [0, 2]
    } as Record<string, any>,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  },
  orderPayTimeWayDict: [] as ISelectDataType[],
  provider: {
    show: false,
    loading: false,
    data: {} as Record<string, any>,
    filterValue: {
      name: "",
      nickName: "",
      providerNo: "",
      status: []
    } as Record<string, any>,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  },
  saleContractsFileList: [] as Record<string, any>[],
  purchaseContractsFileList: [] as Record<string, any>[],
  customsDocFileList: [] as Record<string, any>[],
  ticketDocFileList: [] as Record<string, any>[],
  billDocFileList: [] as Record<string, any>[],
  marginDocFileList: [] as Record<string, any>[]
});

/**
 * 初始化表单数据。
 * 根据不同的操作模式（新增、编辑、查看），加载不同的数据。
 * @param id - ID，用于编辑和查看模式下查询信息。
 */
const initFormData = async (id = "") => {
  await getOrderPayTimeWayDict();
  await getOrderIncotermsDict();
  await getPortTypeDictData();
  if (props.mode !== "new") {
    // } else if (props.mode === "edit" || props.mode === "view") {
    const resultData = await http("GET", `${GET_FORM_PATH}?id=${encodeURIComponent(id)}`);
    pageData.formData = { ...resultData.data };

    if (pageData.formData.products.length > 0 && !pageData.formData.products.some((item: null) => item === null)) {
      pageData.formData.products.forEach((item: any) => {
        item.localUUID = uuidv4();
      });
    }

    // 处理后端数据使之符合表单数据格式
    if (pageData.formData.orderCustomerType === 0) {
      pageData.formData.orderCustomerTypeName = pageData.formData.customer?.name;
    } else if (pageData.formData.orderCustomerType === 1) {
      pageData.formData.orderCustomerTypeName = pageData.formData.customer?.englishName;
    }
    pageData.formData.orderCustomerName = pageData.formData.customer?.name;
    pageData.formData.providerName = pageData.formData.provider?.name;

    pageData.customerTypeSelectData = [
      {
        label: pageData.formData.customer?.name,
        value: 0
      },
      {
        label: pageData.formData.customer?.englishName,
        value: 1
      }
    ];

    if (pageData.formData.saleContractsId !== "" && pageData.formData.saleContractsId !== null) {
      pageData.saleContractsFileList = [
        {
          name: pageData.formData.saleContracts?.name,
          url: `/api/upload/${pageData.formData.saleContracts?.fileURI}`,
          size: pageData.formData.saleContracts?.size,
          status: "success"
        }
      ];
    }

    if (pageData.formData.purchaseContractsId !== "" && pageData.formData.purchaseContractsId !== null) {
      pageData.purchaseContractsFileList = [
        {
          name: pageData.formData.purchaseContracts?.name,
          url: `/api/upload/${pageData.formData.purchaseContracts?.fileURI}`,
          size: pageData.formData.purchaseContracts?.size,
          status: "success"
        }
      ];
    }

    if (pageData.formData.customsDocId !== "" && pageData.formData.customsDocId !== null) {
      pageData.customsDocFileList = [
        {
          name: pageData.formData.customsDoc?.name,
          url: `/api/upload/${pageData.formData.customsDoc?.fileURI}`,
          size: pageData.formData.customsDoc?.size,
          status: "success"
        }
      ];
    }

    if (pageData.formData.ticketDocId !== "" && pageData.formData.ticketDocId !== null) {
      pageData.ticketDocFileList = [
        {
          name: pageData.formData.ticketDoc?.name,
          url: `/api/upload/${pageData.formData.ticketDoc?.fileURI}`,
          size: pageData.formData.ticketDoc?.size,
          status: "success"
        }
      ];
    }

    if (pageData.formData.billDocId !== "" && pageData.formData.billDocId !== null) {
      pageData.billDocFileList = [
        {
          name: pageData.formData.billDoc?.name,
          url: `/api/upload/${pageData.formData.billDoc?.fileURI}`,
          size: pageData.formData.billDoc?.size,
          status: "success"
        }
      ];
    }

    if (Array.isArray(pageData.formData.marginDocIds)) {
      if (pageData.formData.marginDocIds.length !== 0) {
        pageData.marginDocFileList = pageData.formData.marginDocs.map((item: Record<string, any>) => {
          return {
            id: item.id,
            name: item.name,
            url: `/api/upload/${item.fileURI}`,
            size: item.size,
            status: "success",
            response: {
              id: item.id,
              name: item.name,
              url: `/api/upload/${item.fileURI}`
            }
          };
        });
      }
    }

    pageData.loading = false;

    if (props.mode === "view") {
      pageData.readOnly = true;
    }

    if (props.mode !== "view" && pageData.formData.hasExpress === true) {
      MessagePlugin.info("当前订单已经出运，因此处于只读状态。", 5000);
      pageData.readOnly = true;
    }
  } else {
    pageData.formData.orderId = `DHP${generateFormattedNumber()}`;
    pageData.loading = false;
  }
};

const getOrderIncotermsDict = async () => {
  const resultData = await getDictValue("ORDER_INCOTERMS");
  if (resultData.code === 200) {
    const orderIncotermsDict = resultData.data.map((item: Record<string, any>) => {
      return {
        label: item.dictName,
        value: item.dictValue
      };
    });
    pageData.orderIncotermsDict = orderIncotermsDict;
  }
};

const processExchangeData = () => {
  const usdData = props.exchange.exchangeRate.find((item: Record<string, any>) => item.foreignCName === "USD");
  pageData.usdData = usdData;
};

const getCustomerData = async () => {
  pageData.customer.loading = true;
  const resultData = await getCustomerList(
    pageData.customer.pagination.current,
    pageData.customer.pagination.pageSize,
    pageData.customer.filterValue
  );

  if (resultData.code === 200) {
    pageData.customer.data = resultData.data;
    pageData.customer.pagination.total = resultData.data.total;
    pageData.customer.pagination.current = resultData.data.current;
    pageData.customer.pagination.pageSize = resultData.data.size;
    pageData.customer.loading = false;
  }
};

const handleCustomerShow = () => {
  pageData.customer.show = true;
  pageData.customer.pagination = structuredClone(PAGINATION_VALUE);
  pageData.customer.filterValue = {};
  getCustomerData();
};

/**
 * 处理客户确认事件的函数
 * 此函数在客户选择界面确认选择后触发，负责更新表单数据中的客户信息
 * 它将所选客户的ID、客户编号和详细信息分别更新到表单数据的相应字段中
 * 同时，根据所选客户的信息更新客户类型选择数据，以适应界面中可能需要的客户类型选择功能
 * 最后，隐藏客户选择界面，完成整个选择流程
 *
 * @param {Record<string, any>} e - 包含所选客户信息的事件对象
 *        该对象必须包含当前行数据（currentRowData），其中至少包括客户的ID、客户编号和名称
 */
const handleCustomerConfirm = (e: Record<string, any>) => {
  pageData.formData.orderCustomerId = e.options.currentRowData.id;
  pageData.formData.orderCustomerName = e.options.currentRowData.name;
  pageData.formData.customer = e.options.currentRowData;
  pageData.customerTypeSelectData = [
    {
      label: e.options.currentRowData.name,
      value: 0
    },
    {
      label: e.options.currentRowData.englishName,
      value: 1
    }
  ];
  pageData.customer.show = false;
};

const handleCustomerClose = () => {
  pageData.customer.show = false;
};
const handleCustomerPageChange = (pageInfo: Record<string, any>) => {
  // console.log(pageInfo, newDataSource);
  pageData.customer.pagination.pageSize = pageInfo.pageSize;
  pageData.customer.pagination.current = pageInfo.current;
  getCustomerData();
};

const handleCustomerFilterChange = (filters: Record<string, any>) => {
  pageData.customer.filterValue = filters;
  pageData.customer.pagination = structuredClone(PAGINATION_VALUE);
  getCustomerData();
};

const getRegionData = async () => {
  pageData.region.loading = true;
  const resultData = await getRegionList(
    pageData.region.pagination.current,
    pageData.region.pagination.pageSize,
    pageData.region.filterValue
  );

  if (resultData.code === 200) {
    pageData.region.data = resultData.data;
    pageData.region.pagination.total = resultData.data.total;
    pageData.region.pagination.current = resultData.data.current;
    pageData.region.pagination.pageSize = resultData.data.size;
    pageData.region.loading = false;
  }
};

const getPortTypeDictData = async () => {
  const resultData = await getDictValue("PORT_TYPE");
  if (resultData.code === 200) {
    const typeDict = resultData.data.map((item: Record<string, any>) => {
      return {
        label: item.dictName,
        value: item.dictValue
      };
    });
    pageData.portTypeDict = typeDict;
  }
};

const getOrderPayTimeWayDict = async () => {
  const resultData = await getDictValue("ORDER_PAYTIMEWAY");
  if (resultData.code === 200) {
    const orderPayTimeWayDict = resultData.data.map((item: Record<string, any>) => {
      return {
        label: item.dictName,
        value: item.dictValue
      };
    });
    pageData.orderPayTimeWayDict = orderPayTimeWayDict;
  }
};

const handleRegionShow = () => {
  pageData.region.show = true;
  pageData.region.pagination = structuredClone(PAGINATION_VALUE);
  pageData.region.filterValue = {};
  getRegionData();
};

const handleRegionConfirm = (e: Record<string, any>) => {
  pageData.formData.targetCountryId = e.options.currentRowData.id;
  pageData.formData.targetCountry = e.options.currentRowData.countryName;
  handleRegionClose();
};

const handleRegionClose = () => {
  pageData.region.show = false;
};

const handleRegionFilterChange = (filters: Record<string, any>) => {
  pageData.region.filterValue = filters;
  pageData.region.pagination = structuredClone(PAGINATION_VALUE);
  getRegionData();
};

const handleRegionPageChange = (pageInfo: Record<string, any>) => {
  pageData.region.pagination.pageSize = pageInfo.pageSize;
  pageData.region.pagination.current = pageInfo.current;
  getRegionData();
};

const handleProviderShow = () => {
  pageData.provider.show = true;
  pageData.provider.pagination = structuredClone(PAGINATION_VALUE);
  pageData.provider.filterValue = {};
  getProviderData();
};

const handleProviderFilterChange = (filters: Record<string, any>) => {
  pageData.provider.filterValue = filters;
  pageData.provider.pagination = structuredClone(PAGINATION_VALUE);
  getProviderData();
};

const handleProviderConfirm = (e: Record<string, any>) => {
  pageData.formData.provider = e.options.currentRowData;
  pageData.formData.providerName = e.options.currentRowData.name;
  pageData.formData.providerId = e.options.currentRowData.id;
  pageData.provider.show = false;
};
const handleProviderClose = () => {
  pageData.provider.show = false;
};

const getProviderData = async () => {
  pageData.provider.loading = true;
  const GET_LIST_PATH = "/provider/findAll"; // 查询信息接口
  const resultData = await http(
    "POST",
    `${GET_LIST_PATH}?currentPage=${pageData.provider.pagination.current}&pageSize=${pageData.provider.pagination.pageSize}`,
    pageData.provider.filterValue
  );
  if (resultData.code === 200) {
    pageData.provider.data = resultData.data;
    pageData.provider.pagination.total = resultData.data.total;
    pageData.provider.pagination.current = resultData.data.current;
    pageData.provider.pagination.pageSize = resultData.data.size;
    pageData.provider.loading = false;
  }
};

const handleProviderPageChange = (pageInfo: Record<string, any>) => {
  pageData.provider.pagination.pageSize = pageInfo.pageSize;
  pageData.provider.pagination.current = pageInfo.current;
  getProviderData();
};

// 找出数组下标
const findGoodsArrIndex = (row: Record<string, any>) => {
  return pageData.formData.products.findIndex((item: Record<string, any>) => item.localUUID === row.localUUID);
};

/**
 * 处理商品表格选择变化事件
 * 当用户在商品表格中选择或取消选择行时调用此函数
 * 它根据选中的行的键来过滤商品数据，并更新选中行的数据
 *
 * @param keys {Array<Number | String>} - 选中的行的键数组，可以是数字或字符串
 */
const handleGoodsTableSelectChange = ({ keys }: { keys: Array<Number | String> }) => {
  // TDesign 那个多选筛选的 options 数据有点问题，所以要自己过滤一下。
  const filteredObjects = pageData.formData.products.filter((item: Record<string, any>) =>
    keys.includes(item.localUUID)
  );
  pageData.goodsSelectedRowData = filteredObjects;
};

/**
 * 处理新增商品的方法
 * 该方法用于创建一个新的商品表单数据对象，并将其添加到商品列表中
 * 主要步骤包括：
 * 1. 将页面数据中的空商品表单数据转换为原始对象
 * 2. 克隆该原始对象以创建新的商品数据对象
 * 3. 为新的商品数据对象生成唯一的本地UUID
 * 4. 将新的商品数据对象添加到页面表单数据的商品列表中
 */
const handleNewGood = () => {
  const emptyGoodFormDataToRaw = toRaw(pageData.emptyGoodFormData);
  const emptyGoodFormData = structuredClone(emptyGoodFormDataToRaw);
  emptyGoodFormData.localUUID = uuidv4();
  pageData.formData.products.push(emptyGoodFormData);
};

/**
 * 处理复制商品信息的操作
 * 此函数旨在将当前选中的商品行数据进行复制，并以新生成的本地UUID标记这些复制的数据项
 * 它首先检查是否有选中的行，如果没有，则显示错误消息并退出函数
 * 然后，它会创建选中行数据的深拷贝，为每个复制的数据项生成新的UUID，并标记为未删除
 * 最后，将这些复制的数据项添加到表单数据的products数组中
 */
const handleCopyGood = () => {
  if (pageData.goodsSelectedRowData.length === 0) {
    MessagePlugin.error("没有选中行！");
    return;
  }

  // 深拷贝选中的商品行数据，以避免修改原始数据
  const newFormData = JSON.parse(JSON.stringify(pageData.goodsSelectedRowData));
  newFormData.forEach((item: Record<string, any>) => {
    item.localUUID = uuidv4();
    item.hasDeleted = 0;
  });
  pageData.formData.products = [...pageData.formData.products, ...newFormData];
};

const handleDeleteGood = (row: Record<string, any>) => {
  const index = findGoodsArrIndex(row);
  if (index > -1) {
    pageData.formData.products[index].hasDeleted = 1;
  }
};

const handleUnDeleteGood = (row: Record<string, any>) => {
  const index = findGoodsArrIndex(row);
  if (index > -1) {
    pageData.formData.products[index].hasDeleted = 0;
  }
};

const handlePurchaseContractsFileUpload = async (files: Record<string, any>) => {
  const formData = new FormData();

  formData.append("files", files.raw);

  try {
    const res = await uploadFileMany(formData);
    if (res.code === 200) {
      pageData.formData.purchaseContractsId = res.data[0].id;
      return { status: "success" };
    } else {
      return { status: "fail" };
    }
  } catch (error) {
    console.error("上传文件时发生错误:", error);
    return { status: "fail" };
  }
};

const handlePurchaseContractsFileUploadRemove = () => {
  pageData.formData.purchaseContractsId = "";
  pageData.purchaseContractsFileList = [];
};

const handleSaleContractsFileUpload = async (files: Record<string, any>) => {
  const formData = new FormData();

  formData.append("files", files.raw);

  try {
    const res = await uploadFileMany(formData);
    if (res.code === 200) {
      pageData.formData.saleContractsId = res.data[0].id;
      return { status: "success" };
    } else {
      return { status: "fail" };
    }
  } catch (error) {
    console.error("上传文件时发生错误:", error);
    return { status: "fail" };
  }
};

const handleSaleContractsFileUploadRemove = () => {
  pageData.formData.saleContractsId = "";
  pageData.saleContractsFileList = [];
};

const handleCustomsDocFileUpload = async (files: Record<string, any>) => {
  const formData = new FormData();

  formData.append("files", files.raw);

  try {
    const res = await uploadFileMany(formData);
    if (res.code === 200) {
      pageData.formData.customsDocId = res.data[0].id;
      return { status: "success" };
    } else {
      return { status: "fail" };
    }
  } catch (error) {
    console.error("上传文件时发生错误:", error);
    return { status: "fail" };
  }
};

const handleCustomsDocFileUploadRemove = () => {
  pageData.formData.customsDocId = "";
  pageData.customsDocFileList = [];
};

const handleTicketDocFileUpload = async (files: Record<string, any>) => {
  const formData = new FormData();

  formData.append("files", files.raw);

  try {
    const res = await uploadFileMany(formData);
    if (res.code === 200) {
      pageData.formData.ticketDocId = res.data[0].id;
      return { status: "success" };
    } else {
      return { status: "fail" };
    }
  } catch (error) {
    console.error("上传文件时发生错误:", error);
    return { status: "fail" };
  }
};

const handleTicketDocFileUploadRemove = () => {
  pageData.formData.ticketDocId = "";
  pageData.ticketDocFileList = [];
};

const handleBillDocFileUpload = async (files: Record<string, any>) => {
  const formData = new FormData();

  formData.append("files", files.raw);

  try {
    const res = await uploadFileMany(formData);
    if (res.code === 200) {
      pageData.formData.billDocId = res.data[0].id;
      return { status: "success" };
    } else {
      return { status: "fail" };
    }
  } catch (error) {
    console.error("上传文件时发生错误:", error);
    return { status: "fail" };
  }
};

const handleBillDocFileUploadRemove = () => {
  pageData.formData.billDocId = "";
  pageData.billDocFileList = [];
};

const handleMarginDocFileUpload = async (files: Record<string, any>) => {
  const formData = new FormData();

  files.forEach((item: Record<string, any>) => {
    formData.append("files", item.raw);
  });

  try {
    const res = await uploadFileMany(formData);
    if (res.code === 200) {
      return {
        status: "success",
        response: { url: `/api/upload/${res.data[0].fileURI}`, id: res.data[0].id, name: res.data[0].name }
      };
    } else {
      return { status: "fail" };
    }
  } catch (error) {
    console.error("上传文件时发生错误:", error);
    return { status: "fail" };
  }
};

const handleMarginDocFileUploadRemove = () => {
  pageData.formData.marginDocIds = pageData.marginDocFileList.map((item: Record<string, any>) => item.response.id);
};

const handleMarginDocFileUploadSuccess = (e: Record<string, any>) => {
  pageData.formData.marginDocIds = e.response.map((item: Record<string, any>) => item.id);
};

watch(
  () => pageData.formData.products,
  (newVal: Record<string, any>) => {
    if (Array.isArray(newVal) && newVal.length > 0) {
      const totalProductNumber = newVal.reduce((pre: number, cur: Record<string, any>) => {
        return pre + Number(cur.number);
      }, 0);

      const totalPurchasePriceSum = newVal.reduce((pre: number, cur: Record<string, any>) => {
        return pre + Number(cur.totalPurchasePrice);
      }, 0);

      const totalSalePriceSum = newVal.reduce((pre: number, cur: Record<string, any>) => {
        return pre + Number(cur.totalSalePrice);
      }, 0);

      pageData.formData.totalProductNumber = totalProductNumber;
      pageData.formData.totalPurchasePriceSum = newPrecision(totalPurchasePriceSum, 2);
      pageData.formData.totalSalePriceSum = newPrecision(totalSalePriceSum, 2);

      pageData.formData.totalPurchasePrice = newPrecision(totalPurchasePriceSum, 2);
    }
  },
  { deep: true, flush: "post" }
);

/**
 * 提交表单。
 * 根据不同的操作模式（新增、编辑），调用不同的接口保存信息。
 */
const handleSubmit = async () => {
  const validateResult = await formInstance?.value?.validate();

  /* validateResult 在校验没通过的时候返回的是一个 Object，校验通过的时候返回的是
   * 布尔值 true，所以这里写死判断为 true。
   */
  if (validateResult !== true) {
    MessagePlugin.warning("请检查所有选项卡的必填项是否输入完毕。");
    return;
  }

  let resultData;

  if (props.mode === "view" || pageData.formData.hasExpress === true) {
    handleClose();
    return;
  }

  if (pageData.formData.customsDocId === "" || pageData.formData.customsDocId === null) {
    MessagePlugin.error("报关文件没有正确上传！");
    return;
  }

  if (pageData.formData.ticketDocId === "" || pageData.formData.ticketDocId === null) {
    MessagePlugin.error("电子发票文件没有正确上传！");
    return;
  }

  if (pageData.formData.billDocId === "" || pageData.formData.billDocId === null) {
    MessagePlugin.error("提单文件没有正确上传！");
    return;
  }

  if (pageData.formData.marginDocIds.length === 0) {
    MessagePlugin.error("保证金文件没有正确上传！");
    return;
  }

  // console.log(toRaw(pageData.formData));
  const postFormData = toRaw(pageData.formData);

  // 排除尚未保存但已被标记删除的数据
  postFormData.products = postFormData.products.filter(
    (item: Record<string, any>) => !(item.id === "" && item.hasDeleted === 1)
  );

  if (props.mode === "new") {
    // 新增
    resultData = await http("POST", CREATE_FORM_PATH, postFormData);
  } else {
    resultData = await http("POST", UPDATE_FORM_PATH, postFormData);
  }

  // 根据接口返回结果，提示操作成功或失败，并关闭对话框
  if (resultData.code === 200) {
    emits("close", "success");
  }
};

const handleClose = () => {
  emits("close", "cancel");
};

// 如果是查看模式，设置表单为只读
if (props.mode == "view") {
  pageData.readOnly = true;
}

// 初始化表单数据，根据传入的 ID
initFormData(props.id);
processExchangeData();
</script>
